<?php

declare(strict_types=1);
/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://hyperf.wiki
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf/hyperf/blob/master/LICENSE
 */

namespace xsl\services;

use App\Common\Repositories\System\CustomerAdminRepository;
use App\Model\Excel;
use Exception;
use Hyperf\Coroutine\Coroutine;
use Hyperf\Logger\LoggerFactory;
use Psr\Log\LoggerInterface;

class ExcelService
{
    protected LoggerInterface $logger;

    public function __construct(LoggerFactory $loggerFactory)
    {
        // 第一个参数对应日志的 name, 第二个参数对应 config/autoload/logger.php 内的 key
        $this->logger = $loggerFactory->get('hyperf', 'system');
    }

    /**
     * TODO 导出操作.
     * @param array $export
     * @param string $filename
     * @param array $end
     * @param string $suffix
     * @param mixed $id
     * @param mixed $path
     * @param mixed $header
     * @param mixed $title
     */
    public function export($id, $path, $header, $title, $export = [], $filename = '', $end = [], $suffix = 'xlsx')
    {
        try {
            $_path = SpreadsheetExcelService::instance()
                ->createOrActive()
                ->setExcelHeader($header, count($title['mark']) + 2)
                ->setExcelTile($title)
                ->setExcelContent($export)
                ->setExcelEnd($end)
                ->excelSave($filename, $suffix, $path);

            Excel::where('excel_id', $id)->update([
                'name' => $filename . '.' . $suffix,
                'status' => 1,
                'path' => '/' . $_path,
            ]);
        } catch (Exception $exception) {
            Excel::where('excel_id', $id)->update([
                'name' => $filename . '.' . $suffix,
                'status' => 2,
                'message' => $exception->getMessage(),
            ]);
        }
    }

    public function user_excel(array $data)
    {
        go(function () use ($data) {
            Coroutine::sleep(2);
            try {
                $this->logger->info('user_excel：' . json_encode($data));
                $excel_id = $data['excel_id'];
                $where = $data['where'];
                $title = [
                    'title' => '用户信息',
                    'sheets' => '用户信息',
                    'mark' => ['生成时间:' . date('Y-m-d H:i:s', time())],
                ];
                $header = ['ID', '用户名称', '邮箱', '账号', '状态', '创建时间'];
                $filename = '用户信息_' . time();
                $path = 'users';
                $status = [1 => '正常', 2 => '禁用'];
                $export = [];
                \Hyperf\Support\make(CustomerAdminRepository::class)->search($where)
                    ->chunk(100, function ($users) use (&$export, $status) {
                        foreach ($users as $user) {
                            $export[] = [
                                $user->id,
                                $user->username,
                                $user->email,
                                $user->account,
                                $status[$user->status],
                                $user->created_at,
                            ];
                        }
                    });
                $this->export($excel_id, $path, $header, $title, $export, $filename);
            } catch (Exception $e) {
                // Do something.
                $this->logger->error('导出文件:' . $data['type'] . '; error : ' . $e->getMessage() . '--line--' . $e->getLine());
            }
        });
    }
}
